package com.huaxin.hxcloud.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.CLatLng;
import com.huaxin.common.Entity.VehicleRecord;
import com.huaxin.common.message.RouteLineAdapter;
import com.huaxin.common.message.overlayutil.DrivingRouteOverlay;
import com.huaxin.common.message.overlayutil.OverlayManager;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.R;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by Administrator on 2016/11/3.
 */

public class VehicleRoutActivity extends BaseActivity implements OnGetRoutePlanResultListener, BaiduMap.OnMapLoadedCallback, SensorEventListener {

    @BindView(R.id.more)
    ImageView more;
    @BindView(R.id.toolbar)
    Toolbar   toolbar;
    @BindView(R.id.map)
    MapView   mMapView;
    private VehicleRecord vehicleRecord;
    private BaiduMap      mBaiduMap;
    private boolean toLoc = false;

    boolean         useDefaultIcon = false;
    // 搜索相关
    RoutePlanSearch mSearch        = null;    // 搜索模块，也可去掉地图模块独立使用

    DrivingRouteResult nowResultdrive   = null;
    int                nodeIndex        = -1; // 节点索引,供浏览节点时使用
    OverlayManager     routeOverlay     = null;
    boolean            hasShownDialogue = false;
    RouteLine          route            = null;
    private SensorManager                        mSensorManager;
    private LocationClient                       mLocClient;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private MyLocationConfiguration              mConfiguration;
    private BitmapDescriptor                     mCurrentMarker;
    private Polyline mPolyline;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_vehilcle_rout;
    }

    @Override
    public int getLoadFrameId() {
        return R.id.content;
    }

    @OnClick({R.id.more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.more:
                if (mSearch != null) {
                    mSearch.destroy();
                }
                mMapView.onDestroy();
                finish();
                break;
        }
    }


    public static void start(Context context, VehicleRecord vehicleRecord) {
        Intent intent = new Intent(context, VehicleRoutActivity.class);
        intent.putExtra(Constants.IK_VEHICLE_RECORD, vehicleRecord);
        context.startActivity(intent);
    }


    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        if (extras.containsKey(Constants.IK_VEHICLE_RECORD)) {
            vehicleRecord = extras.getParcelable(Constants.IK_VEHICLE_RECORD);
        } else {
            finish();
        }
    }

    @Override
    public void initView() {
        super.initView();
        setSupportActionBar(toolbar);
        toolbar.setTitle("行车路线");
        updateLoadStatus(LOADING);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setOnMapLoadedCallback(this);
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
     //   initSeacher();
        initLocation();
     //   setRouteOverlay(vehicleRecord.getRoute());
    }

    private void initSeacher() {
        // 初始化搜索模块，注册事件监听
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(this);
    }

    /**
     * @desc 初始定位
     * @author songxf
     * created at 2017/7/12 16:03
     */
    private void initLocation() {
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        //开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        //定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(new MyLocationListenner());
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mConfiguration = new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker);
        mBaiduMap.setMyLocationConfigeration(mConfiguration);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setIsNeedAddress(true);
        option.setScanSpan(0);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mBaiduMap == null) {
                return;
            }

            mCurrentAccracy = location.getRadius();
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(6.5f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }
    }

    /**
     * 定位SDK监听函数
     */
    private int    mCurrentDirection = 0;
    private double mCurrentLat       = 0.0;
    private double mCurrentLon       = 0.0;
    private float          mCurrentAccracy;
    private MyLocationData locData;
    boolean isFirstLoc = true; // 是否首次定位
    private Double lastX = 0.0;

    /**
     * @desc 罗盘 旋转改变
     * @author songxf
     * created at 2017/7/12 16:22
     */
    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            mBaiduMap.setMyLocationData(locData);


        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @Override
    public void onMapLoaded() {
        //路线绘制
        updateLoadStatus(LOAD_SUCCESS);
        setRouteOverlay(vehicleRecord.getRoute());
//        if (vehicleRecord.getRoute() == null) {
//            updateLoadStatus(LOAD_ERROR);
//            return;
//        }

        //不显示规划路线
//        final List<CLatLng> route = vehicleRecord.getRoute();
//        try {
////            if (route.size() < 2) {
////                updateLoadStatus(LOAD_ERROR);
////                return;
////            }
//          //  updateLoadStatus(LOAD_SUCCESS);
//            PlanNode stNode = PlanNode.withLocation(new LatLng(route.get(0).getLat(), route.get(0).getLng()));
//            PlanNode enNode = PlanNode.withLocation(new LatLng(route.get(route.size() - 1).getLat(), route.get(route.size() - 1).getLng()));
//            List<PlanNode> nodes = new ArrayList<>();
//            for (CLatLng latLng : route) {
//                nodes.add(PlanNode.withLocation(new LatLng(latLng.getLat(), latLng.getLng())));
//            }
//            mSearch.drivingSearch((new DrivingRoutePlanOption()).from(stNode)
//                    .passBy(nodes).to(enNode));
//            Log.d(TAG, "initSeacher: ---->" + route);
//        } catch (Exception e) {
//            Log.d(TAG, "initSeacher: " + e);
//        }
    }

    public void setRouteOverlay(List<CLatLng> routes) {
        if (routes == null || routes.size() <=2){
            ToastUtil.showToast("暂无路线");
            return;
        }
        // 添加普通折线绘制
        List<LatLng> points = new ArrayList<>();
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (CLatLng latLng : routes) {
            LatLng ltg = new LatLng(latLng.getLat(), latLng.getLng());
            points.add(ltg);
            builder.include(ltg);
        }
        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLngBounds(builder.build());
        mBaiduMap.setMapStatus(mapStatusUpdate);
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomBy(-0.8f);
        mBaiduMap.setMapStatus(msu);
        OverlayOptions ooPolyline = new PolylineOptions().width(10)
                .color(getResources().getColor(R.color.view_green)).points(points);
        mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);
        //以防定位后 改变地图缩放级别
        isFirstLoc=false;
    }


    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_UI);
        super.onResume();
    }

    @Override
    protected void onStop() {
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        if (mSearch != null) {
            mSearch.destroy();
        }
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

    }

    @Override
    public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(VehicleRoutActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            // result.getSuggestAddrInfo()
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            nodeIndex = -1;


            if (result.getRouteLines().size() > 1) {
                nowResultdrive = result;
                if (!hasShownDialogue) {
                    MyTransitDlg myTransitDlg = new MyTransitDlg(VehicleRoutActivity.this,
                            result.getRouteLines(),
                            RouteLineAdapter.Type.DRIVING_ROUTE);
                    myTransitDlg.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            hasShownDialogue = false;
                        }
                    });
                    myTransitDlg.setOnItemInDlgClickLinster(new OnItemInDlgClickListener() {
                        public void onItemClick(int position) {
                            route = nowResultdrive.getRouteLines().get(position);
                            DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaiduMap);
                            mBaiduMap.setOnMarkerClickListener(overlay);
                            routeOverlay = overlay;
                            overlay.setData(nowResultdrive.getRouteLines().get(position));
                            overlay.addToMap();
                            overlay.zoomToSpan();
                        }

                    });
                    myTransitDlg.show();
                    hasShownDialogue = true;
                }
            } else if (result.getRouteLines().size() == 1) {
                route = result.getRouteLines().get(0);
                DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaiduMap);
                routeOverlay = overlay;
                mBaiduMap.setOnMarkerClickListener(overlay);
                overlay.setData(result.getRouteLines().get(0));
                overlay.addToMap();
                overlay.zoomToSpan();

            } else {
                Log.d("route result", "结果数<0");
                return;
            }

        }
    }

    @Override
    public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

    }


    // 供路线选择的Dialog
    class MyTransitDlg extends Dialog {

        private List<? extends RouteLine> mtransitRouteLines;
        private ListView                  transitRouteList;
        private RouteLineAdapter          mTransitAdapter;

        OnItemInDlgClickListener onItemInDlgClickListener;

        public MyTransitDlg(Context context, int theme) {
            super(context, theme);
        }

        public MyTransitDlg(Context context, List<? extends RouteLine> transitRouteLines, RouteLineAdapter.Type
                type) {
            this(context, 0);
            mtransitRouteLines = transitRouteLines;
            mTransitAdapter = new RouteLineAdapter(context, mtransitRouteLines, type);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
        }

        @Override
        public void setOnDismissListener(DialogInterface.OnDismissListener listener) {
            super.setOnDismissListener(listener);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_transit_dialog);

            transitRouteList = (ListView) findViewById(R.id.transitList);
            transitRouteList.setAdapter(mTransitAdapter);

            transitRouteList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    onItemInDlgClickListener.onItemClick(position);

                    dismiss();
                    hasShownDialogue = false;
                }
            });
        }

        public void setOnItemInDlgClickLinster(OnItemInDlgClickListener itemListener) {
            onItemInDlgClickListener = itemListener;
        }

    }

    // 响应DLg中的List item 点击
    interface OnItemInDlgClickListener {
        void onItemClick(int position);
    }

    // 定制RouteOverly
    private class MyDrivingRouteOverlay extends DrivingRouteOverlay {

        public MyDrivingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_st);
            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_en);
            }
            return null;
        }
    }
}
